package de.doegel.common.widget;

import greendroid.widget.item.Item;
import greendroid.widget.itemview.ItemView;

import java.util.List;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AlphabetIndexer;
import android.widget.ArrayAdapter;
import android.widget.SectionIndexer;
import de.doegel.common.IDoegelConstants;
import de.doegel.common.R;
import de.doegel.common.model.Contact;

public class HeadedContactItemAdapter extends ArrayAdapter<HeadedContactItem> implements SectionIndexer {
	protected AlphabetIndexer mIndexer;

	public HeadedContactItemAdapter(Context context, List<HeadedContactItem> items, String sections) {
		super(context, 0, items);
		mIndexer = new AlphabetIndexer(new FakeCursor(this), 0, IDoegelConstants.SECTIONS);
	}

	public int getPositionForSection(int sectionIndex) {
		return mIndexer.getPositionForSection(sectionIndex);
	}

	public int getSectionForPosition(int position) {
		return mIndexer.getSectionForPosition(position);
	}

	public Object[] getSections() {
		return mIndexer.getSections();
	}

	@Override
	public void notifyDataSetChanged() {
		mIndexer = new AlphabetIndexer(new FakeCursor(this), 0, IDoegelConstants.SECTIONS);
		super.notifyDataSetChanged();
	}

	@Override
	public void notifyDataSetInvalidated() {
		mIndexer = new AlphabetIndexer(new FakeCursor(this), 0, IDoegelConstants.SECTIONS);
		super.notifyDataSetInvalidated();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		final HeadedContactItem item = (HeadedContactItem) getItem(position);
		final int section = getSectionForPosition(position);

		if (getPositionForSection(section) == position) {
			String title = mIndexer.getSections()[section].toString().trim();
			item.headerText = title;
		} else {
			item.headerText = null;
		}

		HeadedContactItemView view = (HeadedContactItemView) getItemView(position, convertView, parent);
		Contact contact = (Contact) item.getTag();
		if (contact.image == null && contact.imageBuffer != null && contact.imageBuffer.length > 0) {
			contact.image = BitmapFactory.decodeByteArray(contact.imageBuffer, 0, contact.imageBuffer.length);
		}
		if (contact.image != null) {
			view.imageView.setImageBitmap(contact.image);
		} else {
			view.imageView.setImageResource(R.drawable.empty_contact_image);
		}

		return view;
	}

	public View getItemView(int position, View convertView, ViewGroup parent) {
		final Item item = (Item) getItem(position);
		ItemView cell = (ItemView) convertView;

		if (cell == null) {
			cell = item.newView(getContext(), null);
			cell.prepareItemView();
		}

		cell.setObject(item);

		return (View) cell;
	}
}